<?php

namespace app\controller\teacher;

use app\BaseController;
use app\model\Question;
use \think\facade\Db;

/**
 * 教师-题目控制器
 */
class TeacherQuestion extends BaseController
{
    /**
     * 教师题目列表
     */
    public function listQuestion()
    {
        $QID = $this->request->param('QID','not null');
        $tag = $this->request->param('tag','%');
        $type = $this->request->param('type','not null');
        $pageSize = $this->request->param('pageSize',10);
        $questionList = Question::where(["TID"=>$this->user['TID'],"courseID"=>$this->request->param("courseID")])
        ->where('QID',$QID)
        ->whereLike('tag',$tag)
        ->where('type',$type)
        ->paginate($pageSize);
        return resultSuccess($questionList);
    }
    /**
     * 标签列表
     */
    public function listTag(){
        $tagList = Question::distinct(true)->field(['tag'])->where(["TID"=>$this->user['TID'],"courseID"=>$this->request->param("courseID")])->select();
        return resultSuccess($tagList);
    }

    /**
     * 查找题目
     */
    public function findQuestion()
    {
        $QID = $this->request->param('TID');
        $question = Question::where('TID', $this->user['TID'])->find($QID);
        if (empty($question)) {
            return json(['error']);
        } else {
            return json($question);
        }
    }

    /**
     * 添加题目
     */
    public function addQuestion()
    {
        //var_dump($this->request->param());
        $data = $this->request->param();
        if($data["courseID"]==null){
            return resultError('参数不全');
        }
        $data["QID"] = null;
        $data["TID"] =  $this->user['TID'];
        if($data['tag'] == null){
            $data['tag'] = '未分配';
        }
        $question = new Question($data);
        if ($question->save()) {
            return resultSuccess();
        } else {
            return resultError();
        }
    }

    /**
     * 删除题目
     */
    public function deleteQuestion()
    {
        $QID = $this->request->param("QID");
        $question = Question::where("TID", $this->user['TID'])->find($QID);
        if (empty($question)) {
            return resultError();
        }
        if ($question->delete()) {
            return resultSuccess();
        } else {
            return resultError();
        }
    }

    /**
     * 修改题目
     */
    public function editQuestion()
    {
        $data = $this->request->param();
        $question = Question::where("TID", $this->user['TID'])->find($data['QID']);
        $question['title'] = $data['title'];
        $question['content'] = $data['content'];
        $question['options'] = $data['options'];
        $question['answer'] = $data['answer'];
        $question['tag'] = $data['tag'];
        if($question['tag'] == null){
            $question['tag'] = '未分配';
        }
        if ($question->save()) {
            return resultSuccess();
        } else {
            return resultError();
        }
    }
}
